package com.googlecode.biglog.collector;

import java.io.File;
import java.util.Date;
import java.util.TimerTask;
import java.util.regex.Pattern;

public abstract class AbstractCollector extends TimerTask {
	private String path;
	private String fileNamePattern;
	private Date from;
	private Date to;
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getFileNamePattern() {
		return fileNamePattern;
	}
	public void setFileNamePattern(String fileNamePattern) {
		this.fileNamePattern = fileNamePattern;
	}
	public Date getFrom() {
		return from;
	}
	public void setFrom(Date from) {
		this.from = from;
	}
	public Date getTo() {
		return to;
	}
	public void setTo(Date to) {
		this.to = to;
	}

	@Override
	public void run() {
		File dir = new File(path);
		if (!dir.exists() || !dir.isDirectory())
			return;

		File[] files = dir.listFiles(new FileFilter(fileNamePattern, from, to));
		for (File file : files)
			write(file);
	}
	public abstract void write(File file);

	public static class FileFilter implements java.io.FileFilter {
		private final Pattern pattern;
		private final long from;
		private final long to;
		public FileFilter(String regex, Date from, Date to) {
			super();
			this.pattern = Pattern.compile(regex);
			this.from = from.getTime();
			this.to = to.getTime();
		}
		@Override
		public boolean accept(File file) {
			long lastModified = file.lastModified();
			return lastModified >= from && lastModified <= to && pattern.matcher(file.getName()).matches();
		}
	}
}
